package com.googlesource.gerrit.plugins.examples.servlet.suggestion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gerrit.extensions.annotations.PluginCanonicalWebUrl;
import com.google.gerrit.extensions.annotations.PluginName;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.googlesource.gerrit.plugins.examples.servlet.HttpClientUtil;
import com.googlesource.gerrit.plugins.examples.servlet.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// GET
@Singleton
public class AccountServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(AccountServlet.class);

    @Inject
    AccountServlet(@PluginName String pluginName, @PluginCanonicalWebUrl String url) {
        log.info(String.format("AccountServlet Plugin '%s' at url %s", pluginName, url));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String result = HttpClientUtil
                .sendGet("/accounts/?suggest&q=" + request.getParameter("q"), request)
                .substring(4)
                .trim();
        log.info("accounts result:{}", result);
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(JSON.toJSONString(new Result(200, "SUCCESS", JSONArray.parseArray(result, JSONObject.class))));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
